<template>
  <view class="custom-page">
    <!-- 顶部导航 -->
    <view class="nav-bar" v-if="roles == 'yonghu'">
      <view
        class="nav-item"
        :class="{ active: currentTab === 'user' }"
        @click="currentTab = 'user'"
      >
        发布定制需求
      </view>
      <view
        class="nav-item"
        :class="{ active: currentTab === 'farmer' }"
        @click="currentTab = 'farmer'"
      >
        我的定制需求
      </view>
    </view>

    <!-- 用户端：需求发布 -->
    <view v-if="currentTab === 'user' && roles == 'yonghu'" class="demand-form">
      <view class="form-card">
        <view class="form-item">
          <text class="label">农产品品种</text>
          <input
            v-model="formData.name"
            placeholder="请输入所需农产品品种"
            class="form-input"
          />
        </view>

        <view class="form-item">
          <text class="label">产品规格</text>
          <textarea
            v-model="formData.specifications"
            placeholder="例：有机认证、果径5-6cm、糖度≥12%"
            class="form-textarea"
          />
        </view>

        <view class="form-row">
          <view class="form-item half">
            <text class="label">所需数量</text>
            <input
              v-model="formData.spNumber"
              type="number"
              placeholder="请输入数量(kg)"
              class="form-input"
            />
          </view>
          <view class="form-item half">
            <text class="label">定金</text>
            <input
              v-model="formData.price"
              type="number"
              placeholder="请输入定金(元)"
              class="form-input"
            />
          </view>
          <!-- <view class="form-item half">
            <text class="label">计量单位</text>
            <picker :range="units" v-model="formData.unit">
              <view class="form-picker">
                {{ units[formData.unit] || "选择单位" }}
              </view>
            </picker>
          </view> -->
        </view>

        <view class="form-item">
          <text class="label">期望交付时间</text>
          <picker
            mode="date"
            :value="formData.deliveryTime"
            @change="dateChange"
          >
            <view class="form-picker">
              {{ formData.deliveryTime || "选择日期" }}
            </view>
          </picker>
        </view>

        <button class="submit-btn" @click="submitDemand">发布定制需求</button>
      </view>
    </view>

    <!-- 农户端：需求列表 -->
    <view v-else class="demand-list">
      <view
        v-for="(item, index) in demandList"
        :key="index"
        class="demand-card"
      >
        <view class="demand-header">
          <text class="variety">{{ item.name }}</text>
          <text class="status">{{ item.status }}</text>
        </view>

        <view class="demand-info">
          <view class="info-item">
            <view class="cuIcon-tag"></view>
            <text>规格：{{ item.specifications }}</text>
          </view>
          <view class="info-item">
            <view class="cuIcon-tag"></view>
            <text>定金：{{ item.price }}(元)</text>
          </view>
          <view class="info-item">
            <view class="cuIcon-time"></view>
            <text>交付时间：{{ item.deliveryTime }}</text>
          </view>
          <view class="info-item">
            <view class="cuIcon-cart"></view>
            <text>数量：{{ item.spNumber }}(kg)</text>
          </view>
        </view>

        <view class="action-buttons">
          <!-- <button class="detail-btn" @click="viewDetail(item)">查看详情</button> -->
          <button
            class="accept-btn"
            @click="acceptOrder(item,'已接单')"
            v-if="roles == 'nonghu' && item.remark === null"
          >
            接受订单
          </button>
          <button
            class="accept-btn"
            @click="acceptOrder(item,'已发货')"
            v-if="roles == 'nonghu' && item.remark == '已接单'"
          >
          发货
          </button>
          <button
            class="accept-btn"
            @click="acceptOrder(item,'已完成')"
            v-if="roles == 'nonghu' && item.remark == '已发货'"
          >
          完成订单
          </button>
          <button
            class="accept-btn"
            v-if=" item.remark !== null "
          >
            {{ item.remark }}
          </button>
          <!-- <button
            class="accept-btn"
            v-if=" item.remark == '已接单'"
          >
            已接单
          </button>
          <button
            class="accept-btn"
            v-if=" item.remark == '已完成'"
          >
          已完成
          </button> -->
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentTab: "user",
      units: ["千克", "吨", "箱", "件"],
      formData: {
        name: "",
        specs: "",
        quantity: "",
        unit: 0,
        deliveryTime: "",
      },
      demandList: [
        {
          id: 1,
          name: "有机草莓",
          specs: "果径≥3cm 糖度≥12% 无农残",
          quantity: 200,
          unit: "千克",
          deliveryDate: "2024-03-20",
          status: "待接单",
        },
        {
          id: 2,
          variety: "富硒大米",
          specs: "硒含量≥0.1mg/kg 含水量≤14%",
          quantity: 5,
          unit: "吨",
          deliveryDate: "2024-04-15",
          status: "洽谈中",
        },
      ],
      userInfo: {},
      roles: "",
    };
  },
  onLoad() {
    this.userInfo = uni.getStorageSync("userInfo");
    this.roles = uni.getStorageSync("roles");
    if (this.roles == "nonghu") {
      this.currentTab = "farmer";
    }
    this.getdemandList();
    // }
  },
  onshow() {
    this.getdemandList();
  },
  methods: {
    async getdemandList() {
      let params = {};
      if (this.roles == "yonghu") {
        params = {
          userId: this.userInfo.userId,
        };
      }
      try {
        let res = await this.$api.list("products", params);
        if (res.code == 200) {
          this.demandList = res.rows;
        }
      } catch (error) {}
    },
    dateChange(e) {
      this.formData.deliveryTime = e.detail.value;
    },
    async submitDemand() {
      if (!this.formData.name) {
        return uni.showToast({ title: "请填写农产品品种", icon: "none" });
      }
      if (!this.formData.spNumber) {
        return uni.showToast({ title: "请填写需求数量", icon: "none" });
      }

      // this.demandList.unshift({
      //   ...this.formData,
      //   id: Date.now(),
      //   status: "待接单",
      //   unit: this.units[this.formData.unit],
      // });
      const params = {
        ...this.formData,
        userId: this.userInfo.userId,
      };
      try {
        let res = await this.$api.add("products", params);
        if (res.code == 200) {
          uni.showToast({ title: "需求发布成功" });
          this.resetForm();
        } else {
          uni.showToast({ title: "需求发布失败" });
        }
      } catch (error) {}
    },
    resetForm() {
      this.formData = {
        variety: "",
        specs: "",
        quantity: "",
        unit: 0,
        deliveryDate: "",
      };
    },
    async updateproducts(item,type) {
      let params = {
        id: item.id,
        remark: type,
      };

      try {
        let res = await this.$api.update("products", params);
        if (res.code == 200) {
           this.getdemandList()
        }
      } catch (error) {}
    },
    acceptOrder(item,type) {
      uni.showModal({
        title: "确认接单",
        content: `是否接受定制需求？`,
        success: (res) => {
          console.log("res", res);
          if (res.confirm) {
            // item.status = "已接单";
            this.updateproducts(item,type);
            uni.showToast({ title: "接单成功" });
          }
        },
      });
    },
    viewDetail(item) {
      uni.navigateTo({
        url: `/pages/custom/detail?id=${item.id}`,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.custom-page {
  background: linear-gradient(15deg, #f8f9ff 0%, #f1f3fe 100%);
  min-height: 100vh;
  padding: 24rpx;
}

.nav-bar {
  display: flex;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 48rpx;
  margin: 24rpx 0;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.1);

  .nav-item {
    flex: 1;
    text-align: center;
    padding: 24rpx;
    color: #718096;
    transition: all 0.3s;

    &.active {
      background: linear-gradient(135deg, #667eea, #764ba2);
      color: white;
      border-radius: 48rpx;
      box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
    }
  }
}

.form-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.1);

  .form-item {
    margin-bottom: 32rpx;

    .label {
      display: block;
      color: #667eea;
      font-size: 28rpx;
      margin-bottom: 16rpx;
    }

    .form-input,
    .form-textarea {
      background: #f8f9ff;
      border-radius: 16rpx;
      padding: 24rpx;
      font-size: 28rpx;
    }

    .form-picker {
      background: #f8f9ff;
      border-radius: 16rpx;
      padding: 24rpx;
      color: #2d3748;
    }
  }

  .form-row {
    display: flex;
    gap: 24rpx;

    .half {
      flex: 1;
    }
  }
}

.submit-btn {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border-radius: 48rpx;
  margin-top: 48rpx;
}

.demand-list {
  .demand-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 24rpx;
    padding: 32rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.1);

    .demand-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24rpx;

      .variety {
        font-size: 32rpx;
        color: #2d3748;
        font-weight: 500;
      }

      .status {
        color: #667eea;
        padding: 8rpx 24rpx;
        border-radius: 24rpx;
        background: rgba(102, 126, 234, 0.1);
      }
    }

    .info-item {
      display: flex;
      align-items: center;
      color: #718096;
      margin-bottom: 16rpx;

      .cuIcon {
        margin-right: 12rpx;
        color: #667eea;
      }
    }
  }
}

.action-buttons {
  display: flex;
  gap: 24rpx;
  margin-top: 32rpx;

  button {
    flex: 1;
    border-radius: 48rpx;

    &.detail-btn {
      background: #f1f3fe;
      color: #667eea;
    }

    &.accept-btn {
      background: linear-gradient(135deg, #667eea, #764ba2);
      color: white;
    }
  }
}
</style>
